#include "fs11c14.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
  delay_init();
  led_init();
  uart_init(115200);
  key_init();
  digit_init();
  dht11_init();
  beep_init();
  spi0_init();
  oled_init(255);
  adc_init();
  i2c_init();
  light_init();
  accel_init();
  rfid_init();
  
  puts(__TIME__);
  
  oled_puts(0, 0, "Hello, world");
  oled_puts(2, 0, "Second Line");

  while(1)
  {
    char line[80];
    //有数据返回非空
    if (fgets(line, sizeof(line), stdin))
    {
      puts(line);
      
      switch(line[0])
      {
        case 'l':
          led1_on();
          break;
      
        case 's':
          led1_off();
          break;
      
        case 'd':
          digit_show(segcode[atoi(&line[1])]);
          break;

        case 't':
          //获取温度
          if (dht11_update() == 0)
          {
            printf("t:%.1f\r\n", dht11_temperature());
          }
          break;
      
        case 'h':
          //获取湿度
          if (dht11_update() == 0)
          {
            printf("h:%.1f\r\n", dht11_humidity());
          }
          break;
      
        case 'b':
          beep_tone(atoi(&line[1]));
          break;
      
        case 'v':
          {
            int channel = atoi(&line[1]);
            char bat[16];
            int v = adc_value(channel);
            printf("v:%d\r\n", v);
            sprintf(bat, "AD%d: %d mV", channel, v * 3300/1023);
            oled_puts(4, 0, bat);
          }
          break;
          
        case 'g':
          printf("g:%d\r\n", light_value());
          break;
        
        case 'w':
          if (rfid_present())
          {
            rfid_write_block((uint8_t*)&line[1], strlen(&line[1]));
          }
          break;
          
        case 'r':
          if (rfid_present())
          {
            uint8_t data[16];
            rfid_read_block(data);
            printf("r:%s\r\n", data);
          }
          break;

        default:
          puts("unsupported command");
      }
    }
    
    if (key_esc_pressed())
    {
      puts("ESC pressed");
    }
    
    if (key_up_pressed())
    {
      puts("UP pressed");
    }
  }
}
